package jjn.carl.string;

/**
 * @author Jjn
 * @since 2023/7/5 16:41
 */
public class LeetCode541_2 {
    public String reverseStr(String s, int k) {
        char[] chars = s.toCharArray();
        for (int i = 0; i < s.length(); i = i + 2 * k) {
            int end = Math.min(i + k - 1, s.length() - 1);
            reverse(chars, i, end);
        }
        return new String(chars);
    }
    
    private void reverse(char[] chars, int start, int end) {
        while (start < end) {
            char temp = chars[start];
            chars[start] = chars[end];
            chars[end] = temp;
            start++;
            end--;
        }
    }
    
    public static void main(String[] args) {
        // 如果剩余字符少于 k 个，则将剩余字符全部反转。
        // 如果剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符，其余字符保持原样。
        // bacdfeg
        System.out.println("new LeetCode541().reverseStr(\"abcdefg\", 2) = " + new LeetCode541_2().reverseStr("abcdefg", 2));
        // bacd
        System.out.println("new LeetCode541().reverseStr(\"abcd\", 2) = " + new LeetCode541_2().reverseStr("abcd", 2));
    }
}
